package com.qq2008.game.mojie.server;

import com.alibaba.fastjson.JSON;
import com.qq2008.game.mojie.utils.CommonUtil;
import com.qq2008.game.mojie.jdo.Monster;
import com.qq2008.game.mojie.jdo.Room;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;

/***
 * NPC管理器
 */
@Order(19)
@Component
public class DeadNpcServer implements Runnable, CommandLineRunner {
    // 所有死亡NPC Map
    private static Map<Integer, Monster> deadNpcCache;

    // 更新NPC信息
    public static synchronized void saveDeadNpc(Monster npc) {
        deadNpcCache.put(npc.getId(), npc);
    }

    // 更新NPC信息
    private static synchronized void removeDeadNpc(int npcId) {
        deadNpcCache.remove(npcId);
    }

    //初始化静态参数
    @PostConstruct
    public void init() {
        System.out.println("= 启动地府管理器");
        deadNpcCache = new ConcurrentHashMap<>();
    }


    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                return;
            }
            int nowTime = CommonUtil.getTimestamp();
            deadNpcCache.forEach(new BiConsumer<Integer, Monster>() {
                @Override
                public void accept(Integer npcId, Monster moMonster) {
                    if (nowTime >= moMonster.getReliveTime()) {
                        //
                        int roomId = moMonster.getRoomId();
                        Room room = com.qq2008.game.mojie.server.SceneServer.getRoom(roomId);
                        if (null == room) return;
                        room.getNpcMap().put(npcId, moMonster);
                        // 属性重置
                        Monster npc = com.qq2008.game.mojie.server.NpcServer.getNpc(npcId);
                        npc.setHp(npc.getMaxHP());
                        npc.setMp(npc.getMaxMP());
                        npc.setBattle(null);
                        npc.setReliveTime(0);
                        npc.setDead(false);
                        //
                        deadNpcCache.remove(npcId);

                        System.out.println("怪物 「" + npc.getName() + "」 复活了");
                    }
                }
            });
        }
    }

    @Override
    public void run(String... args) throws Exception {
        Thread thread = new Thread(this);
        thread.start();
    }
}
